<template>
  <el-upload
    class="avatar-uploader"
    :show-file-list="false"
    :http-request="httpRequest"
    :before-upload="beforeUpload"
    :on-success="onSuccess"
    :on-progress="onProgress"
  >
    <div v-if="modelValue" class="box">
      <img :src="modelValue" class="avatar" alt="" />
      <div class="mask">
        <el-icon :size="24" color="#fff" @click.stop="handleDelete">
          <Delete />
        </el-icon>
      </div>
    </div>
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
</template>

<script>
import { uploadAPI } from "@/api/sys.js";
import { ElMessage } from "element-plus";

export default {
  name: "AvatarUpload",
  props: {
    modelValue: String,
    limitSize: {
      type: Number,
      default: 2,
    },
  },
  emits: ["update:modelValue"],
  methods: {
    // 上传之前的
    beforeUpload(rawFile) {
      console.log("beforeUpload", rawFile);
      if (!["image/jpeg", "image/png", "image/gif"].includes(rawFile.type)) {
        ElMessage.error("请上传图片");
        return false;
      } else if (rawFile.size / 1024 / 1024 > this.limitSize) {
        ElMessage.error(`大小限制为${this.limitSize}M`);
        return false;
      }
      return true;
    },
    // 覆盖默认的上传请求
    httpRequest({ file }) {
      return uploadAPI({ file });
    },
    // 上传中的回调函数
    onProgress(evt) {
      console.log("onProgress", evt);
    },
    // 上传成功的回调函数
    onSuccess(response) {
      // response  => http://127.0.0.1:8001/public/uploads/20240201/641cafc0-c0d6-11ee-884e-a71aa0e4d323.jpg
      this.$emit("update:modelValue", response);
    },
    // 删除
    handleDelete() {
      this.$emit("update:modelValue", "");
    },
  },
};
</script>

<style scoped>
.avatar-uploader .box {
  position: relative;
  width: 125px;
  height: 125px;
}
.avatar-uploader .box:hover .mask {
  display: flex;
}
.avatar-uploader .box .mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: none;
  justify-content: center;
  align-items: center;
}
.avatar-uploader .avatar {
  width: 125px;
  height: 125px;
  display: block;
}
.avatar-uploader :deep(.el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 125px;
  height: 125px;
  text-align: center;
}
</style>
